package cn.flyingocean.spider.impl.com.douban.book;

import java.io.*;

public abstract class FileHandlerSpider extends AbstractSpider{
    private BufferedWriter writer;
    private FileOutputStream file_fi = null;
    private OutputStreamWriter file_sr = null;
    /**
     * 获取 BufferedWriter ,惰性加载
     * @return
     */
    public BufferedWriter getWriter(){
        if (writer==null){

            try {
                file_fi = new FileOutputStream(getOutputPath(),true);
                file_sr = new OutputStreamWriter(file_fi, "UTF-8");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            writer = new BufferedWriter(file_sr);
        }
        return writer;
    }

    /**
     * 获得输出路径
     */
    protected abstract String getOutputPath();

    /**
     * spider被 java vm 回收前调用
     */
    public void beforeDead() {
        try {
            writer.close();
            file_sr.close();
            file_fi.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
